<template>
  <div class="page-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumbs">
      <router-link to="/" class="crumb-item">首页</router-link>
      <span class="separator">→</span>
      <router-link to="/user-center" class="crumb-item">我的页面</router-link>
      <span class="separator">→</span>
      <span class="current-crumb">编辑个人信息</span>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <div class="edit-card">
        <h2 class="title">编辑个人信息</h2>

        <div class="form-container">
          <!-- 头像区域 -->
          <div class="avatar-section">
            <div class="avatar-container">
              <div class="avatar-frame">
                <img
                  :src="avatarUrl"
                  alt="用户头像"
                  class="avatar-img"
                  v-if="avatarUrl"
                >
                <div class="default-avatar" v-else>
                  <i class="fa fa-user"></i>
                </div>
                <label class="change-avatar-btn" @click.stop>
                  <input
                    type="file"
                    accept="image/*"
                    class="avatar-input"
                    @change="handleAvatarChange"
                  >
                  <i class="fa fa-camera"></i>
                </label>
              </div>
              <p class="avatar-hint">点击更换头像</p>
            </div>
          </div>

          <!-- 表单区域 -->
          <div class="form-fields">
            <form @submit.prevent="handleSubmit">
              <!-- 第一行：用户名和手机号 -->
              <div class="form-row">
                <div class="form-group">
                  <label for="username" class="form-label">用户名</label>
                  <input
                    type="text"
                    id="username"
                    v-model="formData.username"
                    class="form-input"
                    maxlength="20"
                  >
                  <p class="form-hint">用户名长度不超过20个字符</p>
                </div>

                <div class="form-group">
                  <label for="phone" class="form-label">手机号码</label>
                  <input
                    type="tel"
                    id="phone"
                    v-model="formData.phone"
                    class="form-input"
                    maxlength="11"
                    @input="formatPhone"
                  >
                  <p class="form-hint">请输入有效的11位手机号码</p>
                </div>
              </div>

              <!-- 第二行：邮箱 -->
              <div class="form-row">
                <div class="form-group">
                  <label for="email" class="form-label">电子邮箱</label>
                  <input
                    type="email"
                    id="email"
                    v-model="formData.email"
                    class="form-input"
                  >
                  <p class="form-hint">请输入有效的电子邮箱地址</p>
                </div>
              </div>

              <!-- 当前密码 -->
              <div class="form-row">
                <div class="form-group">
                  <label for="currentPassword" class="form-label">当前密码</label>
                  <input
                    type="password"
                    id="currentPassword"
                    v-model="passwordData.currentPassword"
                    class="form-input"
                    placeholder="请输入当前密码"
                  >
                </div>
              </div>

              <!-- 新密码和确认密码（修复了标签闭合问题） -->
              <div class="form-row">
                <div class="form-group">
                  <label for="newPassword" class="form-label">新密码</label>
                  <input
                    type="password"
                    id="newPassword"
                    v-model="passwordData.newPassword"
                    class="form-input"
                    placeholder="请输入新密码"
                    @input="checkPasswordStrength"
                  >
                  <p class="form-hint">
                    密码长度8-20位，包含大小写字母、数字和特殊字符
                    <span :class="passwordStrengthClass">{{ passwordStrengthText }}</span>
                  </p>
                </div>

                <div class="form-group">
                  <label for="confirmPassword" class="form-label">确认新密码</label>
                  <input
                    type="password"
                    id="confirmPassword"
                    v-model="passwordData.confirmPassword"
                    class="form-input"
                    placeholder="请再次输入新密码"
                  >
                  <p class="form-hint" v-if="passwordData.newPassword && passwordData.confirmPassword">
                    <span :class="passwordMatch ? 'text-success' : 'text-error'">
                      {{ passwordMatch ? '密码一致' : '两次输入的密码不一致' }}
                    </span>
                  </p>
                </div>
              </div>

              <!-- 第三行：性别和出生日期 -->
              <div class="form-row">
                <div class="form-group">
                  <label class="form-label">性别</label>
                  <div class="gender-options">
                    <label class="gender-option">
                      <input
                        type="radio"
                        name="gender"
                        value="male"
                        v-model="formData.gender"
                      >
                      <span>男</span>
                    </label>
                    <label class="gender-option">
                      <input
                        type="radio"
                        name="gender"
                        value="female"
                        v-model="formData.gender"
                      >
                      <span>女</span>
                    </label>
                    <label class="gender-option">
                      <input
                        type="radio"
                        name="gender"
                        value="secret"
                        v-model="formData.gender"
                      >
                      <span>保密</span>
                    </label>
                  </div>
                </div>

                <div class="form-group">
                  <label for="birthday" class="form-label">出生日期</label>
                  <input
                    type="date"
                    id="birthday"
                    v-model="formData.birthday"
                    class="form-input"
                  >
                </div>
              </div>

              <!-- 按钮区域 -->
              <div class="form-actions">
                <button type="button" class="btn cancel-btn" @click="handleCancel">取消</button>
                <button type="submit" class="btn save-btn" :disabled="isSubmitting">
                  <span v-if="!isSubmitting">保存修改</span>
                  <span v-if="isSubmitting">保存中...</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- 成功提示 -->
    <div class="toast" v-if="showToast">
      <p>{{ toastMessage }}</p>
    </div>
  </div>
</template>


<script>
import api from '@/api/request'
import { mapState, mapActions } from 'vuex'

export default {
  data() {
    return {
      // 表单数据
      formData: {
        id: null,
        username: '',
        phone: '',
        email: '',
        realName: '',
        gender: 'secret',
        birthday: ''
      },
      // 头像相关（确保响应式正常）
      avatarUrl: '',
      avatarFile: null,
      // 提交状态
      isSubmitting: false,
      // 提示信息
      showToast: false,
      toastMessage: '',
      passwordData: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordStrength: 0, // 0-弱 1-中 2-强
      passwordStrengthText: '',
      passwordStrengthClass: ''
    };
  },
  computed: {
    ...mapState(['profile']),
    // 检查两次密码输入是否一致
    passwordMatch() {
      return this.passwordData.newPassword === this.passwordData.confirmPassword;
    },
    // 检查密码是否符合格式要求
        isPasswordValid() {
      if (!this.passwordData.newPassword) return true;
      // 与后端规则一致：8位以上，包含大小写字母、数字、特殊字符
      const reg = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>]).{8,20}$/;
      return reg.test(this.passwordData.newPassword);
    }


  },
  created() {
    // 从路由参数或Vuex获取用户信息（初始化头像正常）
    const userData = this.$route.params.userData || this.profile;
    if (userData) {
      this.initFormData(userData);
    } else {
      this.$router.push('/profile');
      this.showToast = true;
      this.toastMessage = '无法获取用户信息';
      this.hideToastAfterDelay();
    }
  },
  methods: {
    ...mapActions(['setProfile']),

    // 初始化表单数据（确保头像URL正确赋值）
    initFormData(userData) {
      this.formData = {
        id: userData.id,
        username: userData.username || '',
        phone: userData.phone || '',
        email: userData.email || '',
        realName: userData.real_name || '',
        gender: userData.gender || 'secret',
        birthday: userData.birthday ? new Date(userData.birthday).toISOString().split('T')[0] : ''
      };

      // 修复：确保头像URL正确拼接（兼容绝对/相对路径）
      if (userData.head_image) {
        this.avatarUrl = userData.head_image.startsWith('http')
          ? userData.head_image
          : `${process.env.VUE_APP_BASE_URL || 'http://127.0.0.1:8000'}/static/${userData.head_image}`;
      }
    },

    // 处理头像上传（本地预览逻辑正常，无需修改）
    handleAvatarChange(e) {
      const file = e.target.files[0];
      if (file) {
        this.avatarFile = file; // 保存文件到响应式变量
        const reader = new FileReader();
        reader.onload = (event) => {
          this.avatarUrl = event.target.result; // 本地预览
        };
        reader.readAsDataURL(file); // 转换为base64
      }
    },

    // 格式化手机号（正常）
    formatPhone() {
      this.formData.phone = this.formData.phone.replace(/\D/g, '');
    },

    // 检查密码强度
    checkPasswordStrength() {
      const password = this.passwordData.newPassword;
      if (!password) {
        this.passwordStrength = 0;
        this.passwordStrengthText = '';
        this.passwordStrengthClass = '';
        return;
      }

      // 简单的密码强度检测
      let strength = 0;
      if (password.length >= 8) strength++;
      // 检查大小写字母同时存在
      if (/[A-Z]/.test(password) && /[a-z]/.test(password)) strength++;
      // 检查数字和特殊字符同时存在
      if (/[0-9]/.test(password) && /[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++;

      this.passwordStrength = strength;

      switch(strength) {
        case 0:
        case 1:
          this.passwordStrengthText = '弱（请增加长度并包含多种字符）';
          this.passwordStrengthClass = 'text-error';
          break;
        case 2:
          this.passwordStrengthText = '中（建议补充特殊字符）';
          this.passwordStrengthClass = 'text-warning';
          break;
        case 3:
          this.passwordStrengthText = '强';
          this.passwordStrengthClass = 'text-success';
          break;
      }
    },

    // 核心修复：确保头像上传无论基本信息是否成功都执行，且跳转逻辑在最后
    async handleSubmit() {
      if (!this.formData.id) {
        this.showToast = true;
        this.toastMessage = '用户信息错误';
        this.hideToastAfterDelay();
        this.isSubmitting = false;
        return;
      }

      if (this.passwordData.newPassword) {
        if (!this.passwordData.currentPassword) {
          this.showToast = true;
          this.toastMessage = '请输入当前密码';
          this.hideToastAfterDelay();
          this.isSubmitting = false;
          return;
        }

        if (!this.isPasswordValid) {
          this.showToast = true;
          this.toastMessage = '新密码必须包含字母和数字，长度6-20位';
          this.hideToastAfterDelay();
          this.isSubmitting = false;
          return;
        }

        if (!this.passwordMatch) {
          this.showToast = true;
          this.toastMessage = '两次输入的密码不一致';
          this.hideToastAfterDelay();
          this.isSubmitting = false;
          return;
        }
      }

      this.isSubmitting = true;
      let isBaseInfoSuccess = true; // 标记基本信息是否成功
      let isPasswordSuccess = true;

      try {
        // 1. 先尝试更新基本信息（即使失败，后续仍执行头像上传）
        const userUpdateData = {
          username: this.formData.username,
          phone: this.formData.phone,
          email: this.formData.email,
          real_name: this.formData.realName,
          gender: this.formData.gender,
          birthday: this.formData.birthday
        };

        try {
          await api.put(`/user/${this.formData.id}`, userUpdateData);
          isBaseInfoSuccess = true;
        } catch (baseError) {
          const errorMsg = baseError.response?.data?.detail || '';
          // 仅当是用户名/邮箱重复时，标记为"可忽略错误"，其他错误仍视为失败
          isBaseInfoSuccess = errorMsg.includes('用户名已存在') ||
                             errorMsg.includes('邮箱已存在') ||
                             errorMsg.includes('username already exists') ||
                             errorMsg.includes('email already exists');
          console.error('基本信息更新提示:', errorMsg); // 仅打印，不中断流程
        }

        // 2. 关键修复：无论基本信息是否成功，只要有头像文件就执行上传
        if (this.avatarFile) {
          const formData = new FormData();
          formData.append('avatar', this.avatarFile); // 确保字段名与后端一致
          await api.put(`/user/${this.formData.id}/avatar`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data' // 正确设置表单类型
            }
          });
          console.log('头像上传成功');
        }

                // 3. 密码修改（核心修复：失败后终止后续流程）
        if (this.passwordData.newPassword) {
          try {
            await api.put(`/user/${this.formData.id}/password_hash`, {
              current_password: this.passwordData.currentPassword,
              new_password: this.passwordData.newPassword,
               confirm_password: this.passwordData.confirmPassword
            });
            isPasswordSuccess = true;
          } catch (passwordError) {
            isPasswordSuccess = false;
            const errorMsg = passwordError.response?.data?.detail || '密码更新失败，请检查当前密码或新密码格式';
            console.error('密码更新失败:', errorMsg);
            // 显示错误并终止流程，不执行后续跳转
            this.showToast = true;
            this.toastMessage = errorMsg;
            this.hideToastAfterDelay();
            this.isSubmitting = false;
            // 直接返回，阻止后续成功提示和跳转
            return;
          }

        }

        // 4. 重新获取最新用户信息（包含可能更新的头像）
        const userResponse = await api.get('/users/me');
        // 更新Vuex和本地存储（确保个人中心能拿到最新数据）
        this.setProfile(userResponse.data);
        localStorage.setItem('userInfo', JSON.stringify(userResponse.data));

        // 5. 提示信息和跳转逻辑
        let message = '';
        if (this.passwordData.newPassword) {
          message = isBaseInfoSuccess
            ? '个人信息和密码保存成功'
            : '密码更新成功，但部分信息未更新';
        } else {
          message = isBaseInfoSuccess ? '个人信息保存成功' : '操作完成（部分信息未更新）';
        }

        // 统一跳转逻辑（无论基本信息是否重复，都跳转）
        this.showToast = true;
        this.toastMessage = message;
        this.hideToastAfterDelay();
        setTimeout(() => {
          this.$router.push('/user-center');
          window.location.reload(); // 刷新确保头像和信息同步
        }, 1000);

      } catch (finalError) {
        console.error('最终处理失败:', finalError);
        // 仅当头像上传或获取用户信息失败时，才提示错误（不跳转）
        this.showToast = true;
        this.toastMessage = '操作失败，请重试';
        this.hideToastAfterDelay();
      } finally {
        this.isSubmitting = false; // 无论结果，都结束提交状态
      }
    },

    // 取消编辑（正常）
    handleCancel() {
      this.$router.go(-1);
    },

    // 延迟隐藏提示（正常）
    hideToastAfterDelay() {
      setTimeout(() => {
        this.showToast = false;
      }, 2000);
    }
  }
};
</script>



<style scoped>

/* 添加密码强度相关样式 */
.text-success {
  color: #4caf50;
  margin-left: 10px;
}

.text-error {
  color: #f44336;
  margin-left: 10px;
}

.text-warning {
  color: #ff9800;
  margin-left: 10px;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f6f0;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 面包屑样式 */
.breadcrumbs {
  margin-bottom: 20px;
  font-size: 14px;
  color: #6d4c2f;
}

.crumb-item {
  color: #8b5a2b;
  text-decoration: none;
}

.crumb-item:hover {
  text-decoration: underline;
}

.separator {
  margin: 0 8px;
}

.current-crumb {
  color: #5d4037;
  font-weight: 500;
}

/* 主要内容样式 */
.main-content {
  padding: 20px 0;
}

.edit-card {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 30px;
}

.title {
  font-size: 22px;
  color: #6d4c2f;
  margin-top: 0;
  padding-bottom: 15px;
  border-bottom: 1px solid #e8d9c4;
}

/* 表单容器 */
.form-container {
  display: flex;
  flex-direction: column;
  gap: 30px;
  margin-top: 25px;
}

@media (min-width: 768px) {
  .form-container {
    flex-direction: row;
  }
}

/* 头像区域 */
.avatar-section {
  display: flex;
  justify-content: center;
}

.avatar-container {
  text-align: center;
}

.avatar-frame {
  position: relative;
  width: 120px;
  height: 120px;
  margin: 0 auto;
}

.avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #d2b48c;
  background-color: #f5f0e6;
}

.default-avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #f5f0e6;
  border: 2px solid #d2b48c;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  color: #8b5a2b;
}

.change-avatar-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #8b5a2b;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  transition: background-color 0.3s;
}

.change-avatar-btn:hover {
  background-color: #6d4c2f;
}

.avatar-input {
  display: none;
}

.avatar-hint {
  margin-top: 10px;
  font-size: 14px;
  color: #8b6e4e;
}

/* 表单字段样式 */
.form-fields {
  flex: 1;
}

.form-row {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
}

@media (min-width: 768px) {
  .form-row {
    flex-direction: row;
  }
}

.form-group {
  flex: 1;
  margin-bottom: 0;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  color: #6d4c2f;
  font-weight: 500;
  font-size: 14px;
}

.form-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d4c0a4;
  border-radius: 4px;
  background-color: #fcfaf7;
  color: #5d4037;
  font-size: 14px;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #8b5a2b;
  box-shadow: 0 0 0 2px rgba(139, 90, 43, 0.2);
}

.form-hint {
  margin: 5px 0 0;
  font-size: 12px;
  color: #8b6e4e;
}

/* 性别选项 */
.gender-options {
  display: flex;
  gap: 20px;
  padding-top: 5px;
}

.gender-option {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #6d4c2f;
  cursor: pointer;
  font-size: 14px;
}

/* 按钮样式 */
.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e8d9c4;
}

.btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  border: none;
}

.cancel-btn {
  background-color: #e8d9c4;
  color: #6d4c2f;
}

.cancel-btn:hover {
  background-color: #d4c0a4;
}

.save-btn {
  background-color: #8b5a2b;
  color: white;
}

.save-btn:hover {
  background-color: #6d4c2f;
}

.save-btn:disabled {
  background-color: #a67c52;
  cursor: not-allowed;
}

/* 提示框样式 */
.toast {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #8b5a2b;
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  animation: fadeIn 0.3s, fadeOut 0.3s 1.7s;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translate(-50%, -20px); }
  to { opacity: 1; transform: translate(-50%, 0); }
}

@keyframes fadeOut {
  from { opacity: 1; transform: translate(-50%, 0); }
  to { opacity: 0; transform: translate(-50%, -20px); }
}
</style>
